package com.bw.service.information.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.information.PiLinkman;
import com.bw.entity.user.TbUser;
import com.bw.mapper.information.PiCustomerMapper;
import com.bw.req.CusLoginMes;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.information.IPiLinkmanService;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import com.bw.utils.sms.SendSms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-15
 */
@Service
public class PiCustomerServiceImpl extends ServiceImpl<PiCustomerMapper, PiCustomer> implements IPiCustomerService {

    public final Logger logger=LoggerFactory.getLogger(PiCustomerServiceImpl.class);
    @Autowired
    private IPiLinkmanService iPiLinkmanService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IPiCustomerService iPiCustomerService;
    @Autowired
    private PiCustomerMapper piCustomerMapper;

    @Override
    public ResponseResult sendCode(String tel) {
        ResponseResult result = ResponseResult.SUCCESS();
        //①判断用户是否存在
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel",tel);
        List list = iPiLinkmanService.list(wrapper);
        if(null==list || list.size()<=0){
            result.setSuccess(false);
            logger.error("用户不存在");
            result.setMessage("用户不存在");
            return result;
        }
        logger.info("用户存在");
        //②判断验证码是否发送频繁(频率最低是一分钟一次)
        //S+手机号存做key  是存储发送频率
        Boolean aBoolean = stringRedisTemplate.boundValueOps("S:" + tel).setIfAbsent("y",1, TimeUnit.MINUTES);
        if(!aBoolean){
            result.setSuccess(false);
            result.setMessage("发送过于频繁");
            return result;
        }
        //③判断当日发送是否达到上限(一天一个手机号十条信息)
        //P+手机号存做key  是存储发送次数
        String num = stringRedisTemplate.boundValueOps("P:" + tel).get();//发送次数
        if(num!=null){
            if(Integer.valueOf(num)>100){
                result.setSuccess(false);
                logger.error("今日次数上限");
                result.setMessage("今日次数上限");
                return result;
            }
        }else{
            stringRedisTemplate.boundValueOps("P:" + tel).expire(1,TimeUnit.DAYS);//存储期限为24小时
        }
        stringRedisTemplate.boundValueOps("P:" + tel).increment();//每次自己加1
        //④发送验证码
        int code= (int) ((Math.random()*9+1)*100000);
        stringRedisTemplate.boundValueOps("Y:"+tel).set(String.valueOf(code),90,TimeUnit.SECONDS);
        logger.info("验证码："+code);
        System.out.println("验证码："+code);
        //使用发送验证码发送短信
//        SendSms.sendSms(tel,String.valueOf(code));
        return result;
    }

    @Override
    public ResponseResult loginByTelAndCode(CusLoginMes cusLoginMes) {
        ResponseResult result = ResponseResult.SUCCESS();
        String code = stringRedisTemplate.boundValueOps("Y:" + cusLoginMes.getTel()).get();
        if(null==code){
            logger.error("验证码过期");
            result.setMessage("验证码过期");
            result.setSuccess(false);
            return result;
        }
        if(!code.equals(cusLoginMes.getCode())){
            logger.error("验证码错误");
            result.setMessage("验证码错误");
            result.setSuccess(false);
            return result;
        }


        //登陆成功，jwt验证
        String token = null;//颁发令牌
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("tel",cusLoginMes.getTel());
            PiLinkman piLinkman = iPiLinkmanService.getOne(wrapper);
            PiCustomer piCustomer = iPiCustomerService.getById(piLinkman.getCustomerId());

            PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\jwt\\key\\rsa.pri");//获取私钥

            UserInfo userInfo=new UserInfo(); //当前登录用户信息
            userInfo.setId(piCustomer.getId());
            userInfo.setUsername(piCustomer.getName());
            token = JwtUtils.generateToken(userInfo,privateKey,360);
            Map mapinfo=new HashMap();
            mapinfo.put("customer",piCustomer);
            mapinfo.put("token",token);
            mapinfo.put("linkman",piLinkman);
            result.setMessage("登录成功");
            result.setResult(mapinfo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常"+e.toString());
        }
        return result;
    }

    @Override
    public List<Map> getTechnologyNum() {
        return piCustomerMapper.getTechnologyNum();
    }

    @Override
    public List<Map> getCustomerNum() {
        return piCustomerMapper.getCustomerNum();
    }
}
